﻿using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Net;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using YuuzleComic.DBUtility;
using System.Threading;
using System.Collections;
using YuuzleComic.DALFactory;
using YuuzleComic.Common;
using System.IO;
using System.Drawing;
using YuuzleComic.Config;
using HtmlAgilityPack;

public partial class yzadmin_data_download : YuuzleComic.Web.UI.ManagePage
{
    protected string json = "";
    public static CookieContainer cookies = new CookieContainer();
    private JObject result = new JObject();
    
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            switch (Request["a"])
            {
                case "list":
                    this.ProcessList();
                    break;
                case "downloadpic":
                    this.ProcessDownloadPic();
                    break;
                case "downloadcomplete":
                    this.downloadComplete();
                    break;
                case "proxylist":
                    this.ProcessProxyList();
                    break;
                case "proxycheck":
                    this.ProcessProxyCheck();
                    break;
                default:
                    break;
            }
        }
    }

    private void ProcessProxyCheck()
    {
        try
        {
            WebClient wc = new WebClient();
            wc.Proxy = new WebProxy(Request["proxy"].Trim());
            result.Add("data", JObject.Parse(wc.DownloadString("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json")));
            result.Add("success", true);
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        finally
        {
            json = result.ToString();
        }
    }

    private void ProcessProxyList()
    {
        try
        {
            List<string> proxyList = new List<string>();
            List<string> ipList = new List<string>();
            HtmlWeb webClient = new HtmlWeb();
            HtmlDocument doc = webClient.Load("http://www.getproxy.jp/cn/china");
            HtmlNodeCollection nodes = doc.GetElementbyId("mytable").SelectNodes("tr[@class]/td[1]");
            foreach (HtmlNode node in nodes)
            {
                if (Input.IsValidIP(node.InnerText.Trim().Split(':')[0]))
                {
                    proxyList.Add(node.InnerText.Trim());
                    ipList.Add(node.InnerText.Trim().Split(':')[0]);
                }
            }

            webClient.OverrideEncoding = System.Text.Encoding.GetEncoding("gb2312");
            doc = webClient.Load("http://proxy.ipcn.org/proxylist.html");
            string[] strArray = doc.DocumentNode.SelectSingleNode("//pre").InnerText.Trim().Split('\n');
            for (int i = 4; i < strArray.Length; i++)
            {
                if (Input.IsValidIP(strArray[i].Trim().Split(':')[0]))
                {
                    proxyList.Add(strArray[i].Trim());
                    ipList.Add(strArray[i].Trim().Split(':')[0]);
                }
            }

            JObject result = JObject.Parse(webClient.Load("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=" + string.Join(",", ipList.ToArray())).DocumentNode.InnerText);
            JArray data = new JArray();
            data.Add(JObject.Parse("{name:'不使用代理',value:''}"));
            data.Add(JObject.Parse("{name:'本地代理[127.0.0.1:8118]',value:'127.0.0.1:8118'}"));
            for (int i = 0; i < proxyList.Count; i++)
            {
                if (result[ipList[i]] != null && result[ipList[i]].ToString() != "-1")
                {
                    JObject jo = new JObject();
                    jo.Add("name", result[ipList[i]]["province"].ToString() + "|" + result[ipList[i]]["city"].ToString() + "|" + result[ipList[i]]["isp"].ToString() + "[" + proxyList[i] + "]");
                    jo.Add("value", proxyList[i]);
                    data.Add(jo);
                }
            }
            json = data.ToString();
        }
        catch (Exception)
        {
            
        }
    }

    private void downloadComplete()
    {
        try
        {
            if (!string.IsNullOrEmpty(Request["zjid"]))
            {
                DbHelperSQL.ExecuteSql("update zj set isdownload=1 where id in (" + Request["zjid"] + ")");
                result.Add("success", true);
            }
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        finally
        {
            json = result.ToString();
        }
    }

    private void ProcessDownloadPic()
    {
        try
        {
            string url = Request["url"];
            string tpadd = Request["tpadd"];
            tpadd = HttpUtility.UrlDecode(tpadd);
            if (url.Contains("http://"))
            {
                string filename = tpadd + url.Substring(url.LastIndexOf("/"));
                if (!System.IO.Directory.Exists(tpadd))//如果不存在就创建文件夹
                {
                    System.IO.Directory.CreateDirectory(tpadd);
                }
                if (!System.IO.File.Exists(filename))
                {
                    this.saveImage(url, filename);
                }
            }
            result.Add("success", true);
            //HttpContext.Current.ApplicationInstance.CompleteRequest();
        }
        catch (Exception e)
        {
            result.Add("success", false);
            result.Add("errorMessage", e.Message);
        }
        finally {
            json = result.ToString();
        }
    }

    private void ProcessList()
    {
        SqlParameter[] parameters = new SqlParameter[] {
            new SqlParameter("@start",Convert.ToInt32(Request["start"]) + 1),
            new SqlParameter("@end",Convert.ToInt32(Request["start"]) + Convert.ToInt32(Request["limit"]))
        };
        DataTable dt = DbHelperSQL.Query("with TT as (select ROW_NUMBER() Over(order by b.id desc) as rowNum, a.mhmc,b.*,STUFF((SELECT ','+ z.zzmc FROM zz z join comics_zz cz on z.id=cz.zzid where cz.cid=a.id FOR XML PATH('')), 1, 1, '') zzmc from comics a join zj b on a.id=b.cid where b.isdownload is null or b.isdownload<>1) select * from TT where rowNum between @start and @end", parameters).Tables[0];
        dt.Columns.Add("exist");
        dt.Columns.Add("existper");
        dt.Columns.Add("directory");
        foreach (DataRow dr in dt.Rows)
        {
            int exist = 0;
            string[] tpurl = dr["tpurl"].ToString().Trim().Split('|');
            foreach (KeyValuePair<string, string> item in YuuzleComic.Config.verConfig.comicDatas)
            {
                if (System.IO.Directory.Exists(item.Value + dr["tpadd"]))//章节文件夹不存在
                {
                    dr["directory"] = item.Key;
                    foreach (string url in tpurl)
                    {
                        string filename = item.Value + dr["tpadd"] + (url.Contains("/") ? url.Substring(url.LastIndexOf("/")) : url);
                        if (System.IO.File.Exists(filename))
                        {
                            exist++;
                        }
                    }
                    break;
                }
            }
            dr["exist"] = exist;
            dr["existper"] = exist * 1.0 / tpurl.Length;
        }
        JsonSerializer serializer = new JsonSerializer();
        serializer.Converters.Add(new JavaScriptDateTimeConverter());
        serializer.NullValueHandling = NullValueHandling.Ignore;
        result.Add("data", JArray.FromObject(dt, serializer));
        result.Add("total", Convert.ToInt32(DbHelperSQL.Query("select count(*) from comics a join zj b on a.id=b.cid where b.isdownload is null or b.isdownload<>1").Tables[0].Rows[0][0]));
        json = result.ToString();
    }

    public void setCookie(string url)
    {
        if (cookies == null || cookies.Count == 0)
        {
            HttpWebRequest myHttpWebRequest = (HttpWebRequest)System.Net.WebRequest.Create(url);
            myHttpWebRequest.Timeout = 20 * 1000; //连接超时
            myHttpWebRequest.Accept = "*/*";
            myHttpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0;)";
            myHttpWebRequest.CookieContainer = new CookieContainer(); //暂存到新实例
            myHttpWebRequest.GetResponse().Close();
            cookies = myHttpWebRequest.CookieContainer; //保存cookies
        }
    }

    public void saveImage(string imgUrl, string imgPath)
    {
        HttpWebRequest myHttpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(imgUrl);//moviePath为图片的真实URL  
        if (DataCache.GetCache("refererDomain") != null && DataCache.GetCache("refererServerList") != null)
        {
            string refererDomain = DataCache.GetCache("refererDomain").ToString();
            List<string> refererServerList = (List<string>)DataCache.GetCache("refererServerList");
            foreach (string server in refererServerList)
            {
                if (imgUrl.Contains(server))
                {
                    myHttpWebRequest.Referer = refererDomain;//伪造网址
                    break;
                }
            }
        }

        string host = new Uri(imgUrl).Host;
        string indexPage = "http://www" + host.Substring(host.IndexOf(".")) + "/"; ;
        if (string.IsNullOrEmpty(myHttpWebRequest.Referer) && !Input.IsValidIP(host))
        {
            myHttpWebRequest.Referer = indexPage.Replace("jmmh.net", "jmydm.com");//伪造网址
        }
        if (host.Contains("xindm"))
        {
            this.setCookie(indexPage);
        }

        if (!string.IsNullOrEmpty(Request["proxy"]))
        {
            myHttpWebRequest.Proxy = new WebProxy(Request["proxy"]);
        }
        
        myHttpWebRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0;)";
        myHttpWebRequest.CookieContainer = cookies;
        System.Net.HttpWebResponse response = myHttpWebRequest.GetResponse() as System.Net.HttpWebResponse;
        System.IO.Stream responseStream = response.GetResponseStream();
        System.Drawing.Image img = System.Drawing.Image.FromStream(responseStream);
        try
        {
            img.Save(imgPath);
        }
        catch (Exception)
        {
            #region 解决gdi+一般性错误
            Bitmap newBmp = new Bitmap(img);
            newBmp.Save(imgPath, System.Drawing.Imaging.ImageFormat.Jpeg);
            newBmp.Dispose(); 
            #endregion
        }
        responseStream.Close();
        response.Close();
    }
}